import { intl } from '@/utils';
import { ExclamationCircleOutlined, WarningOutlined } from '@ant-design/icons';
import { Menu, Modal, Progress, Row } from 'antd';
import notify from 'devextreme/ui/notify';
import moment from 'moment';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import type { DraggableData, DraggableEvent } from 'react-draggable';
import Draggable from 'react-draggable';
import { history, useModel } from 'umi';
import ChangeTemplatePopup from '~/public/cpas-business/components-bs/components/TemplatePopup/ChangeTemplatePopup';
import SaveTemplatePopup from '~/public/cpas-business/components-bs/components/TemplatePopup/SaveTemplatePopup';
import { DevPopup, LayoutB } from '~/public/cpas-ui';
import AntTabs from '~/public/cpas-ui/components-ui/ant-components/AntTab';
import DevDefaultPopup from '~/public/cpas-ui/components-ui/express-components/DevPopup';
import { msgError } from '../../utils/msg';
import { getReportList } from '../batchSettings/service';
import FullNamePupop from "../components/CommonCpasTable/fullNamePupop";
import PageLoading from "../components/PageLoading";
import './index.less';
import { getSeekAuditReportTemplate, getfindDesignTableName, getjudgmentInit, gettableIsVerifyList, templateInitApi } from "./service";

import {
  createReport,
  createVersion,
  exportExcelReport,
  exportReport,
  getDataId,
  getVersions,
  gnoteTreeList,
  initTemplate,
  notesIsEmpty,
  openReport,
  queryAnyFileIfExistInDiskRelativePath,
  saveTemplate
} from './service';
import type { CreateReportProgressInfo, ProgressInfo } from './typings';

const AuditMergeHistory: React.FC = () => {
  const { initialState } = useModel('@@initialState');
  const { dbname, sjxmbh, zcbfid, sjnd, XMType, bsdw } = initialState?.curPart;
  const oneLevelItem = [
    {
      key: 1,
      label: '历史合并记录1',
    },
    {
      key: 2,
      label: '历史合并记录2',
    },
    {
      key: 3,
      label: '历史合并记录3',
    },
  ];
  let fileNameArr = ['', '报告正文.docx', '报告附注.docx', '财务报表.xlsx'];
  const [processPanelVisible, setProcessPanelVisible] = useState(false);
  const [dialogVisible, setDialogVisible] = useState(false);
  const [versionList, setVersionList] = useState<string[]>([]);

  // const [currentTemplateName, setCurrentTemplateName] = useState('');
  // const [isDisclosureTableListVisible, setIsDisclosureTableListVisible] = useState(false);
  const [disclosureTablesData, setDisclosureTablesData] = useState([]);
  //const [selectedDisclosureTable, setSelectedDisclosureTable] = useState([]);
  const selectedDisclosureTable = useRef([]); // 选中的note
  const [dialogTipText, setDialogTipText] = useState('');
  const [isCreateReportSuccess, setIsCreateReportSuccess] = useState(false);
  // const [currentFileName, setCurrentFileName] = useState('报告正文.docx');
  const [currentMenuKey, setCurrentMenuKey] = useState('1');
  const [dataId, setDataId] = useState('2023');
  const versionDialogRef = useRef<any>(null);
  const treeViewRef = useRef<any>(null);
  const saveTemplatePopupRef = useRef<any>();
  const changeTemplatePopupRef = useRef<any>();
  const timer = useRef<any>();
  const projectBase = `/ProjectData/${sjxmbh}/${zcbfid}/报告/`;
  const projectTemplatePath = `${projectBase}/Template`;
  const [disabled, setDisabled] = useState(true);
  const [bounds, setBounds] = useState({
    left: 0,
    top: 0,
    bottom: 0,
    right: 0,
  });
  const [seconds, setSeconds] = useState(0);
  const [isReportOpen, setIsReportOpen] = useState(false);
  const draggleRef = useRef<HTMLDivElement>(null);
  const [spinLoad, setSpinLoad] = useState<boolean>(false);

  //进度条相关

  const [progressInfo, setProgressInfo] = useState<ProgressInfo>({
    progressText: '',
    progressValue: 0,
  });
  const allNoteList = useRef<any>();
  const mergeStartTime = useRef<number>(0);
  //const vserionNote = useRef({ noteList: [], cellDataList: [] });  // 存储历史版本的选中状态，随时可变
  const allNotes = useRef({ noteList: [], cellDataList: [] }); // 存储初始的节点，存储当前版本的选中状态吗，全局不变

  const [currentVersion, setCurrentVersion] = useState<string>('请选择');
  const [isError, setIsError] = useState<string>('');
  const userInfoStr = window.localStorage.cpasUserInfo;
  const userInfo = JSON.parse(userInfoStr);
  //@ts-ignore
  const password = window.main.cryptoUtil(userInfo.aesPassword);

  // 一级侧边栏导航点击事件
  const onItemClick = async (e: any) => {
    setCurrentMenuKey(e.key);
  };

  const getNoteVersion = async (basePath: string, version: string) => {
    //@ts-ignore
    let notes_arr = await window.main.mainObject.loadJsonFromFile(
      `${window.main.mainObject.getAppPath()}${basePath}\\${version}\\Note${version}.json`,
    );

    if (notes_arr?.notes) {
      return notes_arr.notes;
    } else {
      return null;
    }
  };

  const SaveNoteVersion = async (basePath: string, version: string, data: any) => {
    //@ts-ignore
    let config = await window.main.mainObject.saveContentToFile(
      { notes: data },
      `${window.main.mainObject.getAppPath()}${basePath}\\${version}\\Note${version}.json`,
    );
  };
  const treeViewSelectionChanged = async (e: any) => {
    syncSelection(e.component);
  };
  const syncSelection = (treeView: any) => {
    const selectedEmployees = treeView.getSelectedNodes().map((node: any) => node.itemData);
    selectedDisclosureTable.current = selectedEmployees; // 生成报告提交选中节点
  };

  const doCreateReport = async () => {
    console.log(initialState, 'initialState');
    startSetInterval();
    const noteCount = selectedDisclosureTable?.current?.length ?? 0;
    if (noteCount == 0) {
      return msgError(
        intl('cs.notSelectReportNote', '还没有选择附注,请在【左侧->财务报表附注】中选择.'),
      );
    }
    setIsError('');
    setSeconds(0);
    setProcessPanelVisible(true);
    const ids = selectedDisclosureTable.current.map((item: any) => item.id);
    const startTime = performance.now();
    mergeStartTime.current = startTime;
    //setMergeStartTime(startTime);
    const params = {
      projectId: sjxmbh,
      partId: zcbfid,
      dataId,
      ids,
      zcbfid,
      id: mergeStartTime.current,
      noteList: allNoteList.current.map((a: any) => {
        return { ...a, id: `${a.id}-zl`, fid: `${a.fid}-zl`, pid: a.pid ? `${a.pid}-zl` : null };
      }),
    };
    //存在这个方法,用新的,消息通讯方式
    //@ts-ignore
    if (window.main?.createReport) {
      //@ts-ignore
      await window.main?.createReport(params); //在 window_message_event 中处理进度数据
    } else {
      //使用http请请求方式
      console.log('使用http请请求方式,开始创建报告');
      const data = await createReport(params);
      let dataLsit = await getReportList({ dbname: zcbfid, isDesc: true });
      let res = await exportExcelReport({
        resSetting: dataLsit.data,
        dbname: zcbfid,
        //@ts-ignore
        directoryPath: `${window.main.mainObject.getAppPath()}${projectBase}Generated`,
        projectName: bsdw,
        zcbfid: zcbfid,
      });
      console.log(res, 'res');
      if (!res.ok) {
        notify('生成财务报表失败', 'error', 5000);
      }
      await createReportOnFinsh(startTime, selectedDisclosureTable.current);
    }
  };
  //创建结束处理
  async function createReportOnFinsh(startTime: number, selectedDisclosureTableV1: any) {
    stopSetInterval();
    console.log(
      '报告创建结束,开始处理',
      selectedDisclosureTableV1,
      selectedDisclosureTable.current,
    );

    //SaveNewVersionReport('当前版本', selectedDisclosureTable.current);
    await SaveNoteVersion(projectBase, 'Generated', {
      noteList: allNotes.current.noteList,
      cellDataList: selectedDisclosureTable.current,
    } as any);
    // await initVersions()
    // onOpenVersionSelect('当前版本')
    // setCurrentVersion('当前版本');
    setIsReportOpen(false);
    const endTime = performance.now();
    //耗时秒
    const takeSeconds = '(耗时 ' + ((endTime - startTime) / 1000).toFixed(0) + ' 秒)';

    // console.log(isError)
    setIsCreateReportSuccess(true);
    setDialogTipText(` 报告生成成功${takeSeconds}，是否现在立即打开生成的报告文档？`);

    setProcessPanelVisible(false);
    setDialogVisible(true);
  }

  async function initVersions() {
    const data = await getVersions({ projectId: sjxmbh, partId: zcbfid });
    if (data.data?.length) {
      //1,Generated
      //2,Generated,'当前版本'
      //3,Generated,'当前版本', xxxx
      //1,currentVersion === 'Generated' ? '当前版本' : currentVersion
      const arr = data.data.filter((a: any) => a !== 'Generated' && a !== '当前版本');
      setVersionList(['当前版本'].concat(arr) as any);
      //setCurrentVersion('当前版本');
      return data.data;
    } else {
      setVersionList([].concat([]));
      return [];
    }
  }

  async function initTemplateOnLoad() {
    let data = await getSeekAuditReportTemplate({ zcbfid });
    // console.log('当前模板：', data.data.AuditReportTemplate);
    const templateName = data.data.AuditReportTemplate;
    data = await queryAnyFileIfExistInDiskRelativePath({
      filePath: projectTemplatePath,
    });
    // setCurrentTemplateName(templateName);
    //console.log('1111', data);
    if (!data.data) {
      initTemplate({
        templateName,
        copyFilesToWhere: projectTemplatePath,
      });
    }
  }

  async function initDisclosureTables() {
    let dataID = await getDataId({ dbName: zcbfid });
    if (!dataID.ok || dataID.data.length == 0) {
      return msgError(intl('rp.notFoundYear', '未获取到年度'));
    }
    setDataId(dataID.data[0].Data_ID);
    const data = await gnoteTreeList({
      zcbfid: zcbfid,
      Data_ID: dataID.data[0].Data_ID,
      dbName: zcbfid,
    });
    // let Celldata = await CellDataTidList({ zcbfid: zcbfid, Data_ID: dataID.data[0].Data_ID, dbName: zcbfid });
    // debugger
    let Celldata: any = await notesIsEmpty({ zcbfid: zcbfid, dataId: dataID.data[0].Data_ID });

    if (Celldata.data?.length) {
      Celldata = Celldata.data.map((a: any) => {
        return { tid: a.fid };
      });
      allNotes.current.noteList = data.data;
      allNotes.current.cellDataList = Celldata;
      setCurrentNote(data.data, Celldata, true);
      //setCurrentVersion('请选择');
      return data.data;
    } else {
      notify('附注列表无数据，请先初始化附注分析', 'error', 1000);
    }
  }

  async function setCurrentNote(note: [], tids: object[], isF?: boolean) {
    const items = note.map((item: any) => {
      if (item.pid === null) {
        delete item.pid;
      }
      if (isF) {
        item.selected =
          item.isDisclosure === true && !tids.map((a: any) => a.tid || a.id).includes(item.id); // 有数据的，有表的选中
      } else {
        item.selected =
          item.isDisclosure === true && tids.map((a: any) => a.tid || a.id).includes(item.id); // 有数据的，有表的选中
      }

      return item;
    });
    setDisclosureTablesData(items as []);
    const selectedNodes = items.filter((item: any) => {
      return item.selected;
    });
    selectedDisclosureTable.current = selectedNodes as [];
    allNoteList.current = items as [];
  }

  const startSetInterval = useCallback(() => {
    // const start = performance.now();
    timer.current = setInterval(() => {
      const cur = performance.now();
      setSeconds(Math.trunc((cur - mergeStartTime.current) * 0.001));
    }, 900);
  }, [processPanelVisible]); // 依赖进度条
  const stopSetInterval = useCallback(() => {
    return clearInterval(timer.current);
  }, []);
  useEffect(() => {
    initVersions(); // 首次进入查询是否存在版本
    initDisclosureTables();
    initTemplateOnLoad();
  }, []);

  const onStart = (_event: DraggableEvent, uiData: DraggableData) => {
    const { clientWidth, clientHeight } = window.document.documentElement;
    const targetRect = draggleRef.current?.getBoundingClientRect();
    if (!targetRect) {
      return;
    }
    setBounds({
      left: -targetRect.left + uiData.x,
      right: clientWidth - (targetRect.right - uiData.x),
      top: -targetRect.top + uiData.y,
      bottom: clientHeight - (targetRect.bottom - uiData.y),
    });
  };

  //消息 ipcRenderer.on('exportImportData-progress', (event, params) =>
  async function window_message_event(e: any) {
    const params: CreateReportProgressInfo = e.data; //jsonObject
    console.log(params.isError ? params : '');
    if (params.msgType == 'createReport-progress' && params.xmbh === sjxmbh) {
      if (params.id === mergeStartTime.current) {
        updateMergeProgressInfo(params.progressValue, params.progressText);
        // console.log(params.progressText,params.progressText.includes("进程"))
        if (params.isError) {
          stopSetInterval();
          if (params.retData || params.progressText.includes('生成报告失败')) {
            console.log(isError, params.retData, '1');

            setIsReportOpen(false);
            setProcessPanelVisible(false);
            setIsCreateReportSuccess(false);
            setDialogVisible(true);
            setDialogTipText(`报告生成出错：${params.retData || params.progressText}`);
          } else {
            setIsError(isError.concat(`${params.retData || params.progressText}`));
          }
          // console.log(isError,params.retData)
        } else if (params.isFinished) {
          createReportOnFinsh(mergeStartTime.current, []);
        }
        if (params.progressText.includes('附注索引生成完成')) {
          let dataLsit = await getReportList({ dbname: zcbfid, isDesc: true });
          let res = await exportExcelReport({
            resSetting: dataLsit.data,
            dbname: zcbfid,
            //@ts-ignore
            directoryPath: `${window.main.mainObject.getAppPath()}${projectBase}Generated`,
            projectName: bsdw,
            zcbfid: zcbfid,
          });
          console.log(res, 'res');
          if (!res.ok) {
            stopSetInterval();
            notify('生成财务报表失败', 'error', 5000);
          }
        }
      }
    } else {
      if (params.xmbh) {
        stopSetInterval();
        // TODO 如果不加这个判断，现在任何调用浏览器下载弹出的窗口. 都会提示以下错误 , 这需要整改，不能用这种方式来判断报告生成是否有其他项目正在进行
        notify(`有正在生成的其他项目【${params.xmbh}】,请不要同时生成`, 'error', 2000);
      }
    }
  }
  useEffect(() => {
    //接受electron的proload.ts中下载事件 ipcRenderer.on('downloadStart'
    window.addEventListener('message', window_message_event);
    return () => {
      window.removeEventListener('message', window_message_event);
    };
    //treeViewRef.current.
  }, []);

  /**确认生成报告 */
  /**
   *
   * @param e 点击事件
   * @param mergeStartTime 生成报告开始时间
   */
  const exportReportOrTem = async (e?: any) => {
    //@ts-ignore
    const result = await window.electronComponents.openDirectoryDialog();
    // console.log(result)
    if (!result.canceled) {
      // let version = currentVersion ? currentVersion : 'Generated';
      // if (version === '当前版本') {
      //   version = 'Generated';
      // }
      const fileUrl = `${result.filePaths[0]}\\${
        e.itemData === '导出报告' ? '审计报告' : '报告模板'
      }`;

      const exportfile = async () => {
        const res = await exportReport({
          projectId: sjxmbh,
          partId: zcbfid,
          version: currentVersion,
          targetDir: fileUrl,
          isTemplate: e.itemData === '导出报告' ? false : true,
        });
        if (res.ok) {
          notify('导出成功', 'success');
        } else {
          notify('导出失败,请选择版本，或者检查该版本下的文件是否关闭', 'error');
        }
      };
      //@ts-ignore
      if (window.main.fileExists(fileUrl)) {
        //@ts-ignore
        const fileexists = window.main.msgYesNo('该路径下已存在此文件，是否覆盖');
        if (fileexists) {
          exportfile();
        }
      } else {
        exportfile();
      }
    }
  };

  /***
   * * 事件函数： openReportOrtem
   */
  const openReportOrtem = async (e?: any) => {
    const params: any = {
      projectId: sjxmbh,
      partId: zcbfid,
      fileName: fileNameArr[parseInt(currentMenuKey)],
      isTemplate: e === '打开报告' ? false : true,
      version: currentVersion,
    };
    // if (currentVersion && currentVersion != '当前版本') {
    //   params.version = currentVersion;
    // }
    const data = await openReport(params);
    if (!data.ok) {
      notify('未找到报告相关的文件，请确认选择了正确的版本和报告已经生成。', 'error');
    }
  };

  /**
   *
   * 事件函数： onClickSaveNewVersionReport
   */

  const onClickSaveNewVersionReport = async (e: any, isGenerate: boolean = false) => {
    console.log(selectedDisclosureTable.current, '?');
    if (versionList.length) {
      if (versionList.includes(e)) {
        //@ts-ignore
        const fileexists = window.main.msgYesNo('此版本已经存在，是否覆盖');
        if (fileexists) {
          await SaveNewVersionReport(e, selectedDisclosureTable.current);
        }
      } else {
        await SaveNewVersionReport(e, selectedDisclosureTable.current);
      }
    } else {
      notify('当前还未生成报告');
    }
  };

  /**
   * onDeleteVersion
   */
  const onclickDeleteVersion = async (e: any) => {
    //@ts-ignore
    const fileexists = window.main.msgYesNo(`此版本${currentVersion}，是否删除`);
    if (fileexists) {
      try {
        //@ts-ignore
        window.main.mainObject.deleteFolder(
          `${window.main.mainObject.getAppPath()}${projectBase}\\${currentVersion}`,
          false,
        );
        //  await initVersions()
        setVersionList(versionList.filter((item: any) => item !== currentVersion) as any);
        //setCurrentVersion('当前版本') ;
        onOpenVersionSelect('当前版本');
        notify('删除成功');
      } catch (error) {
        notify('删除失败');
      }
    }
  };

  /**
   *
   * onClickOpenSaveVersion
   */
  const onClickOpenSaveVersion = (e: any) => {
    versionDialogRef.current.show({
      title: '保存为新版本',
      value: moment().format('YYYYMMDDHHmm'),
      okCallback: (e: any) => onClickSaveNewVersionReport(e),
    });
  };

  /**
   * onOpenVersionSelect
   */
  const onOpenVersionSelect = async (value: any) => {
    if (value === '当前版本') {
      value = 'Generated';
    }
    let vserionNote = await getNoteVersion(projectBase, value);
    if (vserionNote) {
      setCurrentNote(vserionNote.noteList, vserionNote.cellDataList);
    } else {
      // 没有版本就是当前版本，兼容历史版本
      setCurrentNote(allNotes.current.noteList as [], allNotes.current.cellDataList, true);
    }
    setCurrentVersion(value);
  };

  /**
   * math SaveNewVersionReport
   */
  const SaveNewVersionReport = async (e: any, selectNotedata: any) => {
    let dd = await createVersion({
      projectId: sjxmbh,
      partId: zcbfid,
      version: e,
    });
    console.log(selectedDisclosureTable.current, '?????');
    await SaveNoteVersion(projectBase, e, {
      noteList: allNotes.current.noteList,
      cellDataList: selectNotedata,
    } as any);
    if (dd.ok && dd.data === '') {
      notify(`版本 ${e} 保存成功`);
      await initVersions();
    } else {
      notify(`版本保存失败，请关闭文件`);
    }
  };

  //更新合并进度
  const updateMergeProgressInfo = (
    progressValue: number, //进度数据[0..100]
    progressText?: string, //进度说明
  ) => {
    progressText = progressText;
    setProgressInfo({ progressValue, progressText });
  };
  const ReportTypeList = () => {
    return (
      <div>
        <Menu
          items={oneLevelItem}
          defaultSelectedKeys={[currentMenuKey]}
          onClick={async (e) => {
            await onItemClick(e);
          }}
        />
      </div>
    );
  };

    const [valIndex, setValIndex] = useState<string>('1');
    const [spinAntTabs, setSpinAntTabs] = useState<boolean>(true);
    const [isInitBtn, setIsInitBtn] = useState<boolean>(true);
    const refFullNamePupop = useRef<any>();

    let tableNameGroup = ['审定财务-资产表', '审定财务-负债表', '审定财务-利润表',
        '审定财务-现金流量表', '审定财务-现金流补充资料表', '审定财务-所有者权益变动表_本年', '审定财务-所有者权益变动表_上年', '审定财务-资产减值准备情况表'];
    const [excelParams, setExcelParams] = useState<any>([
        {
            cpastableParam: {
                tname: "审定财务-资产表",
                data_id: "",
                type: "fs",
            },
            // tableTitle: "资产负债表",
            tableDate: " ",
            isExportTableTitle: true,
            exportType: "primary",
            isBatchExport: true
        },
        {
            cpastableParam: {
                tname: "审定财务-负债表",
                data_id: "",
                type: "fs",
            },
            // // tableTitle: "资产负债表（续）",
            tableDate: " ",
            isExportTableTitle: true,
            exportType: "primary",
            isBatchExport: true
        },
        {
            cpastableParam: {
                tname: "审定财务-利润表",
                data_id: "",
                type: "fs",
            },
            // tableTitle: "利润表",
            tableDate: " ",
            isExportTableTitle: true,
            exportType: "primary",
            isBatchExport: true
        },
        {
            cpastableParam: {
                tname: "审定财务-现金流量表",
                data_id: "",
                type: "fs",
            },
            // tableTitle: "现金流量表",
            tableDate: " ",
            isExportTableTitle: true,
            exportType: "primary",
            isBatchExport: true
        },
        {
            cpastableParam: {
                tname: "审定财务-现金流补充资料表",
                data_id: "",
                type: "fs",
            },
            // tableTitle: "现金流量表补充资料",
            tableDate: " ",
            isExportTableTitle: true,
            exportType: "primary",
            isBatchExport: false
        },
        {
            cpastableParam: {
                tname: "审定财务-所有者权益变动表_本年",
                data_id: "",
                type: "fs",
            },
            // tableTitle: "股东(或所有者)权益变动表",
            tableDate: " ",
            isExportTableTitle: true,
            exportType: "primary",
            // isColumnNum: true,: true,
            isBatchExport: true
        },
        {
            cpastableParam: {
                tname: "审定财务-所有者权益变动表_上年",
                data_id: "",
                type: "fs",
            },
            // tableTitle: "股东(或所有者)权益变动表",
            tableDate: " ",
            isExportTableTitle: true,
            exportType: "primary",
            // isColumnNum: true,: true,
            isBatchExport: true
        },

    ]);
    const { pathname, query }: any = window.location || {};

    const [antTabsData, setAntTabsData] = useState<any[]>([
        {
            tabName: '资产',
            tabKey: '1',
            isVerify: false,
            closable: false,
            propsData: {
                tableName: '审定财务-资产表',
                titleName: '资产负债表',
                WscwbbType: '资产类',
                origin: '审定财务',
                tabsIndex: 1,
            }
        },
        {
            tabName: '负债',
            tabKey: '2',
            isVerify: false,
            closable: false,
            propsData: {
                tableName: '审定财务-负债表',
                titleName: '资产负债表（续）',
                WscwbbType: '负债类',
                origin: '审定财务',
                tabsIndex: 2,
            }
        },
        {
            tabName: '利润',
            tabKey: '3',
            isVerify: false,
            closable: false,
            propsData: {
                tableName: '审定财务-利润表',
                titleName: '利润表',
                WscwbbType: '利润类',
                origin: '审定财务',
                tabsIndex: 3,
            }
        },
        {
            tabName: '现流',
            tabKey: '4',
            isVerify: false,
            closable: false,
            propsData: {
                tableName: '审定财务-现金流量表',
                titleName: '现金流量表',
                WscwbbType: '现金流量类',
                origin: '审定财务',
                tabsIndex: 4,
            }
        },
        {
            tabName: '现流附',
            tabKey: '5',
            isVerify: false,
            closable: false,
            propsData: {
                tableName: '审定财务-现金流补充资料表',
                titleName: '现金流量表补充资料',
                WscwbbType: '现金流补充资料类',
                origin: '审定财务',
                tabsIndex: 5,
                actionCol: 2,
            }
        },
        {
            tabName: '权益变动(本年)',
            tabKey: '6',
            isVerify: false,
            closable: false,
            propsData: {
                tableName: '审定财务-所有者权益变动表_本年',
                titleName: '所有者权益变动表',
                WscwbbType: '所有者权益变动表',
                origin: '审定财务',
                tabsIndex: 6,
            }
        },
        {
            tabName: '权益变动(上年)',
            tabKey: '7',
            isVerify: false,
            closable: false,
            propsData: {
                tableName: '审定财务-所有者权益变动表_上年',
                titleName: '所有者权益变动表(续)',
                WscwbbType: '所有者权益变动表(上年)类',
                origin: '审定财务',
                tabsIndex: 7,
            }
        }
    ]);
    const [hideAddBtn, setHideAddBtn] = useState<boolean>(false);
    const refsCommonCpasTable = useRef<any>(null);
    const refsDelte = useRef<any>(1);

    const changeTabsKey = (val: string) => {
        setIsInitBtn(false);
        setValIndex(val);
        history.push('/ReportSys/auditMergeHistory');

    };

    const changeTabs = (changeCur: string) => {
        antTabsData.forEach(item => {
            if (item.propsData.tableName === changeCur) {
                setValIndex(item.tabKey);
            }
        });
    }
    const remove = async (targetKey: any) => {
        // console.log(targetKey);
        // 暂时写死
        await refsCommonCpasTable.current.clearDesignTableName('审定财务-资产减值准备情况表');
        setAntTabsData((item) => {
            let lastIndex: any;
            const tempData = [...item];
            tempData.forEach((pane, i) => {
                if (pane.tabKey === targetKey) {
                    lastIndex = i - 1;
                }
            });
            const newData = tempData.filter(pane => pane.tabKey !== targetKey);

            if (newData.length && valIndex === targetKey) {
                if (lastIndex >= 0) {
                    setValIndex(newData[lastIndex].tabKey);
                } else {
                    setValIndex(newData[0].tabKey);
                }
            }
            return newData;
        });


        // setExcelParams((item: any) => {
        //     const tempData = [...item];
        //     const newData = tempData.filter(pane => pane.tabKey !== targetKey);
        //     return newData;
        // });

        window.localStorage.setItem(`审定财务-资产减值准备情况表-${dbname}`, JSON.stringify({
            isADD: false
        }));
        setHideAddBtn(false);
        notify(`删除资产减值标签页，成功！`, "success", 2000);

    };
    const getDesignTableName = async (funType: string) => {
        let indexD = -1;
        indexD = antTabsData.findIndex((item) => item.propsData.tableName === '审定财务-资产减值准备情况表');
        const res = await getfindDesignTableName({ design_tableName: '审定财务-资产减值准备情况表', dbname });
        if (res.success) {
            if (res.data || funType === 'addTabs') {
                if (indexD < 0) {
                    setAntTabsData((item) => {
                        const newData = [...item];
                        newData.push({
                            tabName: '减值准备',
                            tabKey: '8',
                            isVerify: false,
                            closable: true,
                            propsData: {
                                tableName: '审定财务-资产减值准备情况表',
                                titleName: '资产减值准备情况表',
                                WscwbbType: '资产减值准备情况类',
                                origin: '审定财务',
                                tabsIndex: 8,
                            }
                        });
                        return newData;
                    });
                    window.localStorage.setItem(`审定财务-资产减值准备情况表-${dbname}`, JSON.stringify({
                        isADD: true
                    }));
                    if (funType === 'addTabs') {
                        setValIndex('8');
                    }
                }
                setHideAddBtn(true);
            } else {
                if (indexD > 0) {
                    remove('8');
                }
            }
        }
    };
    const antTabsDetail = async () => {
        const res = await gettableIsVerifyList({ tableName: "审定财务", dbname, isTid: false });
        if (res.success) {
            if (res.data.length > 0) {
                const tempsName = res.data.map((item: { name: string }) => item.name).join(',') || "";
                setAntTabsData((oldData: any) => {
                    const newData = [...oldData];
                    newData.forEach((item: any) => {
                        const msg = item.propsData.tableName;
                        const isName = tempsName.includes(msg);
                        item.isVerify = isName;
                        return item;
                    });
                    return newData;
                });
            } else {
                setAntTabsData((oldData: any) => {
                    const newData = [...oldData];
                    newData.forEach((item: any) => {
                        item.isVerify = false;
                        return item;
                    });
                    return newData;
                });
            }
        } else {
            notify(`获取isVerify校验失败！`, "error", 2000);
        }
    }
    const getAuditReportTemplate = async (isAllInit: boolean, yearTableName: any, actionTabs: any) => {
        try {
            const judg = await getjudgmentInit({
                dbname,
                type: 'fs',
                tableRealName: yearTableName
            });
            if (judg.success) {
                console.log(refsCommonCpasTable.current, '@@@ ');
                if (judg.data?.count_number === 0) {
                    setSpinLoad(true);
                    const res = await getSeekAuditReportTemplate({
                        zcbfid
                    });
                    if (res.success) {
                        let tempObjs: any = {};
                        if (isAllInit) {
                            tempObjs = {
                                tableNames: tableNameGroup,
                            }
                        } else {
                            tempObjs = {
                                tableNames: ["审定财务-资产减值准备情况表"],
                                opt: {
                                    duplicate: "cover"
                                }
                            }
                        }
                        const resTemp: any = await templateInitApi({
                            dbName: dbname,
                            templateName: res.data.AuditReportTemplate,
                            type: 'fs',
                            ...tempObjs
                        });
                        setSpinLoad(false);
                        if (resTemp.success) {
                            notify(`模板初始化成功`, "success", 2000);
                            await getDesignTableName(actionTabs);
                            setTimeout(async () => {
                                if (!refsCommonCpasTable.current) return;
                                await refsCommonCpasTable.current?.CPASInit2(yearTableName, true);
                                await antTabsDetail();
                            }, 300);
                        } else {
                            await getDesignTableName(actionTabs);
                            setTimeout(async () => {
                                if (!refsCommonCpasTable.current) return;
                                await refsCommonCpasTable.current.CPASInit2(yearTableName, false);
                            }, 300);
                            if (res.data.AuditReportTemplate) {
                                notify(`${resTemp.msg}`, "error", 2000);
                            } else {
                                notify(`请在首页组成部分信息内选择报告模板`, "warning", 2000);
                            }
                        }
                    }

                } else {
                    await getDesignTableName(actionTabs);
                    setTimeout(async () => {
                        if (!refsCommonCpasTable.current) return;
                        await refsCommonCpasTable.current.CPASInit2(yearTableName, false);
                        await antTabsDetail();
                    }, 300);
                }
                setIsInitBtn(false);
            } else {
                notify(`获取判断是否初始化失败！`, "error", 2000);
            }
        } catch (error) {
            notify(`获取判断是否初始化失败！`, "error", 2000);
        }
    };
    const add = async () => {
        if (!refsCommonCpasTable.current) return;
        setIsInitBtn(true);// 重要
        console.log(refsCommonCpasTable.current, '@@@ add');
        getAuditReportTemplate(false, "审定财务-资产减值准备情况表", 'addTabs');
        notify(`添加资产减值标签页，成功！`, "success", 2000);
    };


    const onEdit = (
        targetKey: React.MouseEvent | React.KeyboardEvent | string,
        action: 'add' | 'remove',
    ) => {
        if (action === 'add') {
            add();
        } else {
            refsDelte.current.show({
                title: "删除提醒",
                okCallback: () => {
                    remove(targetKey);
                }
            });


        }
    };



    const changeSpinAntTabs = async (newData: boolean, yearTableName: any) => {
        setSpinAntTabs(newData);
        setIsInitBtn(false);
        setValIndex('1');
        if (newData && refsCommonCpasTable.current) {
            await getDesignTableName('');
            refsCommonCpasTable.current.CPASInit2('审定财务-资产表', false);
        }
    }
    useEffect(() => {
        getAuditReportTemplate(true, "审定财务-资产表", '');
    }, []);

    useEffect(() => {
        if (pathname === '/ReportSys/auditMergeHistory' && query.tableName) {
            changeTabs(query.tableName);
        }
    }, [pathname, query]);

    const [tabText1, setTabText1] = useState("");
    const tabsRef: any = useRef(null);
    const tabRef: any = useRef(null);
    const [isRerun, setIsRerun] = useState(false);
    const [activeKey, setActiveKey] = useState("1")
    const AccountTabsClick = (key: string) => {
      console.log(key, 'key----');
      if (key === '2') {
        setIsRerun(false);
      }
      setTabText1(key)
      setActiveKey(key);
    };
    const modileIsReturn = (value: any) => {
      setIsRerun(value);
    };
    useEffect(() => {
      AccountTabsClick('1');
    }, []);
    useEffect(() => {
      console.log(isRerun, 'isRerun---useEffect');
      const notePageRef = tabRef?.current?.notePageRef;
      if (isRerun && tabText1 === "1" && notePageRef?.current?.tab1Init) {
        notePageRef.current.tab1Init();
      }
    }, [isRerun, tabText1]);
    /**
     *
     * @param data
     * @param noVerifyModal 是否打开校验详情弹窗
     */
    const openVerifyDetail = (data: any, noVerifyModal: boolean) => {
      const notePageRef = tabRef?.current?.notePageRef;
      console.log("opendetail---tabsRef", tabsRef);
      console.log(data, 'openDetail data');
      setActiveKey("1");
      // AccountTabsClick('1');
      notePageRef.current.openVerifyDetail(data, noVerifyModal);
      notePageRef.current.tab1SearchTableName(data.title, data.fid);
    }
  return (
    <div style={{ height: 'calc(100vh - 104px)' }} id="report-page-container">
      <Modal
        open={isReportOpen}
        className="report-modal"
        keyboard={false}
        maskClosable={false}
        closable={!processPanelVisible}
        width={500}
        //centered={true}
        destroyOnClose={true}
        forceRender={true}
        title={
          <div
            style={{ cursor: 'move' }}
            onMouseOver={() => {
              if (disabled) {
                setDisabled(false);
              }
            }}
            onMouseOut={() => {
              setDisabled(true);
            }}
          >
            <ExclamationCircleOutlined style={{ color: 'orange' }} /> 确认
          </div>
        }
        onOk={doCreateReport}
        onCancel={() => {
          setProcessPanelVisible(false);
          setIsReportOpen(false);
        }}
        cancelButtonProps={{ disabled: processPanelVisible }}
        okButtonProps={{
          loading: processPanelVisible,
          disabled: processPanelVisible,
        }}
        okText="开始生成"
        cancelText="取消"
        modalRender={(modal) => (
          <Draggable
            disabled={disabled}
            bounds={bounds}
            nodeRef={draggleRef}
            onStart={(event, uiData) => onStart(event, uiData)}
          >
            <div ref={draggleRef}>{modal}</div>
          </Draggable>
        )}
      >
        <div className="report-content">
          已选择附注 {selectedDisclosureTable?.current?.length} 个, 生成报告需要几分钟,
          {processPanelVisible ? '请稍候...' : '是否继续?'}
        </div>
        <div style={{ height: 40, display: processPanelVisible ? 'block' : 'none' }}>
          <Progress percent={progressInfo.progressValue} showInfo={false} />
          <div>
            已完成 {progressInfo.progressValue.toFixed(0)}% 耗时{seconds.toFixed(0)} 秒
            {progressInfo.progressText}
          </div>
        </div>
      </Modal>

      <DevDefaultPopup.Input ref={versionDialogRef} />
      <DevPopup.Logic
        width={500}
        height={250}
        visible={dialogVisible}
        title="提示"
        okCallbackShow={!isCreateReportSuccess}
        cancelText="否"
        okText={isCreateReportSuccess ? '是' : '确定'}
        onOK={async () => {
          // console.log('on ok');
          setDialogVisible(false);
          if (isCreateReportSuccess) {
            await openReport({
              projectId: sjxmbh,
              partId: zcbfid,
              fileName: '报告附注.docx',
            });
          }
        }}
        // cancelDisabled
        onCancel={() => {
          setDialogVisible(false);
        }}
        onHiding={() => setDialogVisible(false)}
      >
        {() => {
          return (
            <div style={{ overflowY: 'auto', height: '85px' }}>
              {isError.length > 0 ? <div>{isError}</div> : ''}
              <br />
              <div>{dialogTipText}</div>
            </div>
          );
        }}
      </DevPopup.Logic>

      <SaveTemplatePopup
        ref={saveTemplatePopupRef}
        okCallback={async (data: any) => {
          //console.log(data, '@@@ 保存模板');
          const res = await saveTemplate({
            templateName: data,
            files: projectTemplatePath,
            isInsertDB: false,
          });
          if (res.ok) {
            saveTemplatePopupRef.current.reloadTemplate();
            notify(`保存模板成功！`, 'success', 2000);
          } else {
            notify(`保存模板失败！`, 'success', 2000);
          }
        }}
        cancelCallback={() => {
          //console.log('@@@ ， 取消');
        }}
      />

      <ChangeTemplatePopup
        ref={changeTemplatePopupRef}
        okCallback={async (data: any) => {
          //console.log(data, '@@@ 切换模板');
          // setCurrentTemplateName(data);
          const res = await initTemplate({
            templateName: data,
            copyFilesToWhere: projectTemplatePath,
          });
          if (res.ok) {
            notify(`切换模板成功！`, 'success', 2000);
          } else {
            notify(`切换模板失败！`, 'success', 2000);
          }
        }}
        cancelCallback={() => {
          //console.log('@@@ ， 取消');
        }}
        changeData={{
          cloudTempType: '报告模板',
        }}
      />
      <Row align={'middle'} wrap={false} className="report-top-box">
        <div className="report-lf">历史合并</div>
        <div className="report-ri">
          <AntTabs
            tabBarStyle={{ background: '#FFF' }}
            onChange={AccountTabsClick}
            className={"report-analysis-tabs"}
            defaultActiveKey="1"
            ref={tabsRef}
            activeKey={activeKey}
          >
            <AntTabs.Panel
              tab='附注'
              key='1'
            >
            </AntTabs.Panel>
            <AntTabs.Panel
              className={"art-count-panel"}
              tab='附注勾稽汇总'
              key='2'
            >
              {/* 开发中。。。 */}
            </AntTabs.Panel>
            {/*<AntTabs.Panel*/}
            {/*  tab='附注波动分析'*/}
            {/*  key='3'*/}
            {/*>*/}
            {/*  /!* <PageTabThree/> *!/*/}
            {/*  开发中。。。*/}
            {/*</AntTabs.Panel>*/}
          </AntTabs>
        </div>
      </Row>
      <div className={currentMenuKey === '2' ? 'finance-report-wrap' : 'report-wrap'}>
        <LayoutB
          rowSize={['10%', '150px', '90%']}
          leftSlot={<ReportTypeList />}
          rightSlot={
            <div className="trialBalance_whole">
            {}
            <PageLoading
                isOpen={spinLoad}
                isMaskClose={false}
                content={"正在初始化..."}
                width={200}
            />
            {spinAntTabs && <AntTabs defaultActiveKey="1"
                className="changeTabsHeight"
                type="editable-card"
                destroyInactiveTabPane={true}
                onChange={(val: string) => { changeTabsKey(val) }} activeKey={valIndex}
                onEdit={onEdit} hideAdd={hideAddBtn}
            >
                {
                    antTabsData.map(item => (
                        <AntTabs.TabPane tab={
                            // <div onDoubleClick={() => handleDoubleClick(item.propsData.tableName, item.tabName)}>
                            <div>
                                <span>{item.tabName}
                                    {item.isVerify && <span className="render-span"
                                        onClick={() => {
                                            if (refsCommonCpasTable.current) {
                                                refsCommonCpasTable.current.CPASOpenDetail();
                                            }
                                        }}>
                                        <WarningOutlined />
                                    </span>}
                                </span>
                            </div>
                        }
                            key={item.tabKey} closable={item.closable} >
                            {/* <CommonCpasTable CPASTableProps={item.propsData} CPASTableTabName={item.tabName}
                                isInitBtn={isInitBtn}
                                changeIsInitBtn={() => {
                                    setIsInitBtn(false);
                                }}
                                biaoAllData={antTabsData}
                                excelParams={excelParams}
                                cpasChangeSpinAntTabs={(data: boolean, yearTableName: any) => { changeSpinAntTabs(data, yearTableName) }} antTabsTabPaneDetail2={() => antTabsDetail()}
                                ref={refsCommonCpasTable}
                                tableNameGroup={tableNameGroup}
                            /> */}
                        </AntTabs.TabPane>
                    ))
                }
            </AntTabs>}
            <DevPopup.Default ref={refsDelte} width={80} height={220}  >
                {() => {
                    return <span>确定要执行此删除操作吗？</span>
                }}
            </DevPopup.Default>

            <FullNamePupop ref={refFullNamePupop} />

        </div>
          }
        />
      </div>



      
    </div>
  );
};

export default AuditMergeHistory;
